package com.port.port_app.service;


import com.fazecast.jSerialComm.SerialPort;
import org.springframework.stereotype.Service;

import javax.xml.bind.DatatypeConverter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SerialService {

    private List<String> atCommandsSent = new ArrayList<>();

    private SerialPort comPort;
    private String charsetName = "ASCII"; // 编码格式：如"UTF-8", "ASCII", "GBK","ISO8859-1","UTF-16"等

    /**
     * 方法1：打开串口
     *
     * @param portName
     * @return
     */
    public String openPort(String portName) {
        // 波特率、数据位、停止位、奇偶校验位
        comPort = SerialPort.getCommPort(portName); // 请根据你的实际串口号进行修改
        comPort.setComPortParameters(9600, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 500, 500);
        if (comPort.openPort()) {
            return "串口已打开" + portName;
        } else {
            return "无法打开串口" + portName;
        }
    }

    /**
     * 方法2：写入数据到串口并返回
     *
     * @param atCommand
     * @return
     */
    public String writeToPort(String atCommand) {
        try {
            OutputStream outputStream = comPort.getOutputStream();
            InputStream inputStream = comPort.getInputStream();
            String atCommands = atCommand + "\n"; // 必须加回车符
            outputStream.write(atCommands.getBytes(charsetName));
            outputStream.flush();
            Thread.sleep(1000);
            // 读取返回的数据
            byte[] readBuffer = new byte[1024];
            int numRead = inputStream.read(readBuffer);
            String response = new String(readBuffer, 0, numRead, charsetName);
            // 提取特定字符串后面的数字部分
            if (response.toString().contains("IMEI")) {
                String imei = extractDigitsAfterKeyword(response, "IMEI:");
                System.out.println("IMEI: " + imei);
                return imei;
            } else if (response.toString().contains("ICCID")) {
                String iccid = extractDigitsAfterKeyword(response, "ICCID:");
                System.out.println("ICCID: " + iccid);
                return iccid;
            } else if (response.toString().contains("SN")) {
                String sn = extractDigitsAfterKeyword(response, "SN:");
                System.out.println("SN: " + sn);
                return sn;
            }
            //关闭
            outputStream.close();
            inputStream.close();
            return null;
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }

    /**
     * 方法3：关闭串口
     */
    public String closePort() {
        if (comPort != null) {
            comPort.closePort();
            return "关闭串口成功";
        }else {
            return "关闭串口失败";
        }
    }

    /**
     * 方法4：临时指令模式
     *
     * @param
     * @return
     */
    public String temporaryMode() {
        try {
            OutputStream outputStream = comPort.getOutputStream();
            InputStream inputStream = comPort.getInputStream();
            outputStream.write("+".getBytes(charsetName));
            outputStream.flush();
            Thread.sleep(10);
            outputStream.write("+".getBytes(charsetName));
            outputStream.flush();
            Thread.sleep(10);
            outputStream.write("+".getBytes(charsetName));
            outputStream.flush();
            Thread.sleep(10);
            Thread.sleep(100);
            Thread.sleep(1000);
            outputStream.write("a".getBytes(charsetName));
            outputStream.flush();
            //关闭
            outputStream.close();
            inputStream.close();
            return "进入临时模式成功";
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }

    /**
     * 提取特定关键词后面的数字部分
     *
     * @param str
     * @param keyword
     * @return
     */
    private static String extractDigitsAfterKeyword(String str, String keyword) {
        String regex = keyword + "\\s*(\\d+)\\s*";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            return matcher.group(1);
        } else {
            return null;
        }
    }

    public void recordATCommandSent(String atCommand) {
        atCommandsSent.add(atCommand);
    }

    public List<String> getAtCommandsSent() {
        return atCommandsSent;
    }

}
